import { createStore, combineReducers, applyMiddleware } from 'redux'
import thunk from 'redux-thunk'
import wsMiddleware from './middleware/ws'

import appReducer, { APP_ACTION } from './reducers/appReducer'
import tradeMarketReducer, { TRADE_MARKET_ACTION } from './reducers/tradeMarketReducer'
import tradeBidAskReducer, { TRADE_BID_ASK_ACTION } from './reducers/tradeBidAskReducer'
import tradeDealDetailReducer, { TRADE_DEAL_DETAIL_ACTION } from './reducers/tradeDealDetailReducer'
import tradeDataQueryReducer, { TRADE_DATA_QUERY_ACTION } from './reducers/tradeDataQueryReducer'
import tradeOrderBoardReducer, { TRADE_ORDER_BOARD_ACTION } from './reducers/tradeOrderBoardReducer'
import tradeChartReducer, { TRADE_CHART_ACTION } from './reducers/tradeChartReducer'
import tradeAssetsReducer, { TRADE_ASSETS_ACTION } from './reducers/tradeAssetsReducer'

const filterActions = (reducer, actionTypes = []) => {
  const predicate = (type) => actionTypes.indexOf(type) > -1
  const initialState = reducer(undefined, {})
  return (state = initialState, action) => {
    if (predicate(action.type)) {
      return reducer(state, action)
    }
    return state
  }
}

const store = createStore(
  combineReducers({
    app: filterActions(appReducer, [APP_ACTION]),
    trade: combineReducers({
      market: filterActions(tradeMarketReducer, [TRADE_MARKET_ACTION]),
      bidAsk: filterActions(tradeBidAskReducer, [TRADE_BID_ASK_ACTION]),
      dealDetail: filterActions(tradeDealDetailReducer, [TRADE_DEAL_DETAIL_ACTION]),
      dataQuery: filterActions(tradeDataQueryReducer, [TRADE_DATA_QUERY_ACTION]),
      orderBoard: filterActions(tradeOrderBoardReducer, [TRADE_ORDER_BOARD_ACTION]),
      chart: filterActions(tradeChartReducer, [TRADE_CHART_ACTION]),
      assets: filterActions(tradeAssetsReducer, [TRADE_ASSETS_ACTION])
    })
  }),
  applyMiddleware(thunk, wsMiddleware)
)

export default store
